/*
 * Copyright (c) 2016
 * 杭州塔酱科技有限公司 版权所有
 */

package com.tajiang.business.mess.fragment;


import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.tajiang.business.R;
import com.tajiang.business.common.application.TJApp;
import com.tajiang.business.common.constant.TJCst;
import com.tajiang.business.common.fragment.BaseFragment;
import com.tajiang.business.common.http.Api;
import com.tajiang.business.common.http.BaseResponse;
import com.tajiang.business.common.http.HttpHandler;
import com.tajiang.business.common.http.HttpResponseListener;
import com.tajiang.business.common.utils.GlideRoundTransform;
import com.tajiang.business.common.utils.ToastUtils;
import com.tajiang.business.common.utils.UserUtils;
import com.tajiang.business.common.widget.LoadingDialog;
import com.tajiang.business.common.widget.dialog.ActionSheetDialog;
import com.tajiang.business.common.widget.dialog.CallDialog;
import com.tajiang.business.mess.activity.BalanceActivity;
import com.tajiang.business.mess.activity.FoodManagementActivity;
import com.tajiang.business.mess.activity.SetStallsNoticeActivity;
import com.tajiang.business.model.SalesStatistics;
import com.tajiang.business.model.User;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.NumberFormat;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 食堂信息
 */
public class MessFragment extends BaseFragment implements OnClickListener, HttpResponseListener {

    private static final int PHOTO_REQUEST_CAMERA = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果
    /* 头像名称 */
    private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
    private File tempFile;

    @BindView(R.id.tv_order)
    TextView tvOrder;
    @BindView(R.id.tv_today_money)
    TextView tvTodayMony;
    @BindView(R.id.tv_sum_money)
    TextView tvSumMoney;
    @BindView(R.id.ll_today_order_awards)
    LinearLayout llTodayOrderAwards;
    @BindView(R.id.icon_header)
    ImageView icon_header;
    @BindView(R.id.tv_store_name)
    TextView tvStoreName;
    @BindView(R.id.tv_withdraw_money)
    TextView tvWithdrawMoney;
    @BindView(R.id.rl_contact_phone)
    RelativeLayout rlContactPhone;

    private static final int SEND_BBS_REQUEST = 3;    //食堂公告

    private NumberFormat numberFormat = NumberFormat.getInstance();
    private LoadingDialog loadingDialog;
    private Bitmap bitmap;
    private String token;
    private Object qiNiuToken;

    @Override
    protected void initTopBar() {
        setTitle("营业统计");
        //消息通知
//        setRightByImgId(R.mipmap.icon_tongzhi);
//        setOnRightClick(new OnRightClick() {
//            @Override
//            public void rightClick() {
//                intent2Activity(NoticeActivity.class);
//            }
//        });
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.fragment_mess);
    }

    @Override
    protected void initData() {
        loadingDialog = new LoadingDialog(getActivity());
        initView();
    }

    private void initView() {
//        tvStoreName.setText(UserUtils.getUser().getRealName() + "");
        Glide.with(getActivity())
                .load(UserUtils.mBusinessAccountInfo.getShopImage())
                .transform(new CenterCrop(getActivity())   //此方式解决CenterCrop与Transformer的共存问题
                        ,new GlideRoundTransform(getActivity(), 4))
                .placeholder(R.mipmap.school_test)
                .error(R.mipmap.school_test)
                .crossFade()
                .into(icon_header);
    }

    @OnClick(R.id.rl_finance)
    void click() {
        intent2Activity(BalanceActivity.class);
    }

    private void updateStatistics(SalesStatistics salesStatistics) {
        tvOrder.setText(String.valueOf(salesStatistics.getSalenumCount() == null ? 0 : salesStatistics.getSalenumCount()));
        tvTodayMony.setText((salesStatistics.getTodayMony() == null || salesStatistics.getTodayMony().doubleValue() == 0) ? "0.00" :
                String.valueOf(salesStatistics.getTodayMony().setScale(2, BigDecimal.ROUND_DOWN).toString()));
        tvSumMoney.setText((salesStatistics.getSumMoney() == null || salesStatistics.getSumMoney().doubleValue() == 0) ? "0.00" :
                String.valueOf(salesStatistics.getSumMoney().setScale(2, BigDecimal.ROUND_DOWN).toString()));
    }

    @Override
    public void onSuccess(BaseResponse response) {
        SalesStatistics salesStatistics = (SalesStatistics) response.getData();
        updateStatistics(salesStatistics);
    }

    @Override
    public void onFailed(BaseResponse response) {

    }

    /**
     * 结束刷新今日有效订单，今日有效提成后
     * 继续后去提现余额。
     */
    @Override
    public void onFinish() {
//        updateBalance();
    }


    /**
     * 获取提现金额
     */
    private void updateBalance() {
        new HttpHandler(new HttpResponseListener() {
            @Override
            public void onSuccess(BaseResponse response) {
                MessFragment.this.tvWithdrawMoney.setText(new BigDecimal(response.getData()
                        .toString()).setScale(2, BigDecimal.ROUND_DOWN).toString());
            }

            @Override
            public void onFailed(BaseResponse response) {

            }

            @Override
            public void onFinish() {
                if (loadingDialog.isShowing()) {
                    loadingDialog.dismiss();
                }
            }
        }).getBalance();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
//        new HttpHandler(this).orderToday();
    }

    //点击底部任务栏，刷新今日有效订单，今日有效提成。。。。
    @Override
    public void reFreshCurrentPageData() {
//        loadingDialog.show();
        super.reFreshCurrentPageData();
        new HttpHandler(this).orderToday();
    }

    @OnClick(R.id.rl_contact_phone)
    public void onPhoneClick() {
        CallDialog callDialog = new CallDialog(getActivity(), TJCst.CUSTOMER_SERVICES_PHONE);
        callDialog.show();
    }

    @OnClick(R.id.icon_header)
    public void onLogoClick() {

    }

    /**
     * 菜品管理
     */
    @OnClick(R.id.rl_food_management)
    public void onFoodManagementClick() {
        intent2Activity(FoodManagementActivity.class);
    }

    @OnClick(R.id.rl_stalls_notice)
    public void onStallsNoticeClick() {
        Intent intent = new Intent();
//        intent.putExtra("store_id", mStore.getId());
        intent2ActivityWidthExtrasAndForResult(intent, SetStallsNoticeActivity.class, SEND_BBS_REQUEST);
    }

    @OnClick(R.id.ll_change_icon)
    public void onChangeIconClick() {
        initChangeIconDialog();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * resultCode == Activity.RESULT_CANCELED
         * 按返回键，退出拍照
         */
        if (resultCode != Activity.RESULT_CANCELED) {
            if (requestCode == PHOTO_REQUEST_GALLERY) {
                if (data != null) {
                    // 得到图片的全路径
                    Uri uri = data.getData();
                    crop(uri);
                }

            } else if (requestCode == PHOTO_REQUEST_CAMERA) {
                if (hasSdcard()) {
                    tempFile = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME);
                    crop(Uri.fromFile(tempFile));

                } else {
                    ToastUtils.showShort("未找到存储卡，无法存储照片！");
                }

            } else if (requestCode == PHOTO_REQUEST_CUT) {
                try {
                    bitmap = data.getParcelableExtra("data");
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);

                    myupload(saveBitmap(bitmap).getPath());

//                    QiniuUtils.upload(TJApp.getInstance().mToken, baos.toByteArray(), new UpCompletionHandler() {
//                        @Override
//                        public void complete(String key, com.qiniu.android.http.ResponseInfo info, JSONObject response) {
//                            try {
//                                doupdateIcon(response.getString("key"));
//                            } catch (JSONException e) {
//                                e.printStackTrace();
//                            }
//                        }
//                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    }

    private void myupload(String path) {

        Log.v("1", path);
        RequestParams params = new RequestParams();
        params.addBodyParameter("appid", "android.merchant");
        params.addBodyParameter("token", TJApp.getInstance().mToken);
        params.addBodyParameter("timestamp", TJApp.getInstance().sendTime);
        params.addBodyParameter("avatar", new File(path), "image/jpg");

        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST,
                TJCst.BASE_URL + Api.user_avatar,
                params, new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String resultStr = responseInfo.result;
                        Log.e("1", "上传成功：" + resultStr);
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Log.e("1", "上传失败：" + error.getExceptionCode() + ":" + msg);
                    }
                });
    }

    private void doupdateIcon(String key) {

        new HttpHandler(new HttpResponseListener() {
            @Override
            public void onSuccess(BaseResponse response) {
                ToastUtils.showShort("修改头像成功");
                String url = (String) response.getData();
                User user = UserUtils.getUser();

//                user.setImage(url);
//                UserUtils.saveUser(user);



                Glide.with(getActivity())
                        .load(url)
                        .transform(new CenterCrop(getActivity())   //此方式解决CenterCrop与Transformer的共存问题
                                ,new GlideRoundTransform(getActivity(), 4))
                        .placeholder(R.mipmap.school_test)
                        .error(R.mipmap.school_test)
                        .crossFade()
                        .into(icon_header);
            }

            @Override
            public void onFailed(BaseResponse response) {

            }

            @Override
            public void onFinish() {

            }
        }).userModifyAvatarReq(key);
    }

    //上传更换头像
    private void initChangeIconDialog() {
        //请求七牛的Token
//        getQiNiuToken();
        new ActionSheetDialog(getActivity())
                .builder()
                .setCanceledOnTouchOutside(true)
                .setTitle("您要更换头像吗？")
                // 点击弹出框之外的地方，弹出框消失
                .setCanceledOnTouchOutside(false)
                .addSheetItem("相册", ActionSheetDialog.SheetItemColor.Green,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onSheetItemClick(int which) {
                                // 激活系统图库，选择一张图片
                                Intent intent = new Intent(Intent.ACTION_PICK);
                                intent.setType("image/*");
                                startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
                            }
                        })
                .addSheetItem("照相", ActionSheetDialog.SheetItemColor.Green,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onSheetItemClick(int which) {
                                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                                // 判断存储卡是否可以用，可用进行存储
                                if (hasSdcard()) {
                                    intent.putExtra(MediaStore.EXTRA_OUTPUT,
                                            Uri.fromFile(new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME)));
                                }
                                startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
                            }
                        })
                .show();
    }

    /**
     * 剪切图片
     *
     * @function:
     * @author:Jerry
     * @date:2013-12-30
     * @param uri
     */
    private void crop(Uri uri) {
        // 裁剪图片意图
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // 裁剪框的比例，1：1
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // 裁剪后输出图片的尺寸大小
        intent.putExtra("outputX", 250);
        intent.putExtra("outputY", 250);
        // 图片格式
        intent.putExtra("outputFormat", "JPEG");
        intent.putExtra("noFaceDetection", true);// 取消人脸识别
        intent.putExtra("return-data", true);// true:不返回uri，false：返回uri
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

    private boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            return true;
        } else {
            return false;
        }
    }

    /** 保存方法 */
    public File saveBitmap(Bitmap bitmap) {

        Log.e("zd", "保存图片");
        File f = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME);
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
            Log.i("zd", "已经保存");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return f;
    }




}
